package org.budo.phone.location.service.qianxing;

import java.io.ByteArrayInputStream;

import org.budo.phone.location.service.api.AbstractBudoPhoneLocation;
import org.budo.phone.location.service.api.BudoPhoneLocation;
import org.budo.phone.location.service.api.BudoPhoneLocationService;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.time.Time;
import org.budo.xml.Xml;
import org.budo.xml.XmlObject;
import org.springframework.util.DigestUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 联系千行游书兵
 * 
 * @author lmw
 */
@Getter
@Setter
@Slf4j
public class QianxingPhoneLocationService implements BudoPhoneLocationService {
    private String url = "http://cardpay.18pingtai.cn:8091/mobile/query";

    private String cid = "taojinqiyezhushou";

    private String key = "44N4XJB6ZFND4Z6Z2ZL20R26RF40Z82L";

    @Override
    public BudoPhoneLocation seekPhoneLocation(String phone) {
        String tsp = Time.now().toString("yyyyMMddHHmmss");
        String sign = DigestUtils.md5DigestAsHex((this.getCid() + phone + tsp + this.getKey()).getBytes());

        Request request = new Request();
        request.setUrl(this.getUrl());
        request.setMethod(Request.POST);

        request.setField("cid", this.getCid());
        request.setField("pn", phone);
        request.setField("tsp", tsp);
        request.setField("sign", sign);

        Response response = request.execute();

        ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getResponseData());
        XmlObject xmlObject = Xml.parse(inputStream);
        XmlObject responseXml = xmlObject.getChildNodeByName("response");
        XmlObject dataXml = responseXml.getChildNodeByName("data");

        String serviceProvider = dataXml.getChildNodeTextContentByName("cn");
        String province = dataXml.getChildNodeTextContentByName("pv");
        String city = dataXml.getChildNodeTextContentByName("ct");

        if ("未知".equals(serviceProvider) && "未知".equals(province) && "未知".equals(city)) {
            log.error("#60 xmlObject=" + xmlObject + ", phone=" + phone);
            return null;
        }

        return new AbstractBudoPhoneLocation(province, city, serviceProvider);
    }
}